import { AnyAction } from 'redux';
import Knowledge from 'constants/knowledge';
import Assist from 'constants/assist';
import Attachment from 'constants/attachment';
import Page from 'constants/page';
import Course from 'constants/course';
import Lesson from 'constants/lesson';
import Tag from 'constants/tag';
import Test from 'constants/test';
import Level from 'constants/level';
import Review from 'constants/review';
import Preview from 'constants/preview';

function initLoading(keys: string[]) {
  let obj: any = {};
  keys.forEach((item: any) => {
    obj[item + '_loading'] = false;
  });
  return obj;
}

const initialState: Record<string, any> = initLoading([
  Course.FETCH,
  Course.CREATE,
  Course.UPDATE,
  Course.FETCH_LIST,
  Course.FETCH_LESSON_LIST,

  Lesson.FETCH,
  Lesson.CREATE,
  Lesson.REMOVE,
  Lesson.FETCH_LIST,
  Lesson.SAVE_COVER,
  Lesson.SAVE_AUDIO,
  Lesson.UPDATE_PUBLISH_STATUS,
  Lesson.FETCH_PRECISION_LIST,
  Lesson.FETCH_TEST_LIST,
  Lesson.SORT_PAGE,
  Lesson.SORT_TEST,

  Knowledge.FETCH,
  Knowledge.FETCH_LIST,
  Knowledge.CREATE,
  Knowledge.UPDATE,
  Knowledge.SAVE_IMAGE,
  Knowledge.SAVE_AUDIO,
  Knowledge.SAVE_TAG,

  Assist.FETCH,
  Assist.FETCH_LIST,
  Assist.CREATE,
  Assist.UPDATE,

  Attachment.REMOVE,
  Attachment.UPDATE,
  Attachment.FETCH_ATTACHMENT_LIST,

  Page.FETCH,
  Page.FETCH_LIST,
  Page.CREATE,
  Page.REMOVE,
  Page.UPDATE,

  Tag.CREATE,
  Tag.REMOVE,
  Tag.FETCH_LIST,

  Test.CREATE,
  Test.REMOVE,
  Test.UPDATE,
  Test.FETCH_LIST,
  Test.CREATE_TPL,
  Test.FETCH_TPL_LIST,
  Test.UPDATE_TPL,

  Level.CREATE,
  Level.REMOVE,
  Level.UPDATE,
  Level.FETCH_LIST,

  Review.CREATE_LEVEL,
  Review.REMOVE_LEVEL,
  Review.UPDATE_LEVEL,
  Review.FETCH_LEVEL_LIST,
  Review.CREATE_WORD,
  Review.REMOVE_WORD,
  Review.UPDATE_WORD,
  Review.FETCH_WORD_LIST,
  Review.CREATE_TEST,
  Review.REMOVE_TEST,
  Review.UPDATE_TEST,
  Review.FETCH_TEST,
  Review.FETCH_TEST_LIST,
  Review.FETCH_TEST_TPL_LIST,

  Preview.CREATE,
  Preview.REMOVE,
  Preview.UPDATE,
  Preview.FETCH_LIST,
  Preview.CREATE_PAGE,
  Preview.REMOVE_PAGE,
  Preview.UPDATE_PAGE,
  Preview.SORT_PAGE,
  Preview.FETCH_PAGE,
  Preview.FETCH_PAGE_LIST,
]);

export default (state = initialState, action: AnyAction) => {
  const { type, payload } = action;
  if (type === 'SET_LOADING') {
    return Object.assign({}, state, {
      [`${payload.scope}_loading`]: payload.loading,
    });
  }

  return state;
};
